package com.xiaodou.mjf.infrastructure.common.controller;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.springframework.data.domain.Page;

import com.google.common.collect.Maps;
import com.xiaodou.mjf.infrastructure.common.components.ResultCode;
import com.xiaodou.mjf.infrastructure.common.entity.CommonEntity;
import com.xiaodou.mjf.infrastructure.common.utils.PropertiesLoader;

/**
 * Created by Rocky on 2/26/15.
 */
public class ApiController extends ApplicationController{


    protected static Properties props = new PropertiesLoader("error_code.properties").getProperties();

    protected Map<String,Object> page(long count,List<? extends CommonEntity> items){
        Map<String,Object> data = Maps.newHashMap();
        data.put("count", count);
        data.put("items", items);
        return data;
    }

    protected Map<String,Object> page(Page<? extends CommonEntity> page){
        Map<String,Object> data = Maps.newHashMap();
        data.put("count", page.getTotalElements());
        data.put("items", page.getContent());
        return data;
    }

    protected Map<String,Object> failure(String code,String message){
    	Map<String,Object> result = Maps.newHashMap();
        result.put("code",code);
        result.put("message",message);
        return result;
    }

    protected Map<String,Object> failure(String code){
    	Map<String,Object> result = Maps.newHashMap();
        result.put("code",code);
        result.put("message",getResource(code));
        return  result;
    }

    protected Map<String,Object> success(){
    	Map<String,Object> result = Maps.newHashMap();
        result.put("code", ResultCode.SUCCESS);
        return result;
    }

    protected Map<String,Object> success(String key,String value){
    	Map<String,Object> result = Maps.newHashMap();
        result = success();
        result.put(key,value);
        return result;
    }

    private String getResource(String code){
        if(props != null){
            return props.getProperty(code);
        }else{
            return "未定义的异常";
        }
    }
}
